
import json

import arrow
import requests
import time
from app import celery

# 创建任务
from tools import MyRedis, MyMongo


@celery.task
def add(a, b):
    n = a + b
    print(n)
    return n
# 监听定时发送

@celery.task
def request_timing_send(data):
    res=requests.get(url='http://127.0.0.1:5002/timing_send/',params={'data':data})
    print(res)
    return 'ok'


@celery.task
def watch_timing_send():
    # 查询定时队列
    with MyRedis() as c:
        timing_list = c.hgetall('timing_send')

    for k, v in timing_list.items():
        # 循环与当前时间戳比较
        timestrap = int(time.mktime(time.strptime(v.decode('utf-8'), '%Y-%m-%d %H:%M:%S')))
        # 如果定时时间等于当前时间 或者 小于当前时间了
        if timestrap == int(time.time()) or timestrap < int(time.time()):
            # 调用异步函数 进行发送请求
            request_timing_send.delay(k.decode('utf-8'))

            if res.status_code==200:
                # 如果成功发送 添加发送时间
                data=eval(k.decode('utf-8'))
                with MyMongo(db='md', table='message_box') as c:
                    n = arrow.now()
                    c.update_one({'title': data['title']}, {'$set': {'sendtime':n.format('YYYY-MM-DD HH:mm:ss')}})
                with MyRedis() as c:
                    c.hdel('timing_send',k.decode('utf-8'))
